package com.bs.bszhsq.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bs.bszhsq.config.AuthAccess;
import com.bs.bszhsq.entity.Files;
import com.bs.bszhsq.entity.Kehu;
import com.bs.bszhsq.mapper.FileMapper;
import com.bs.bszhsq.service.FileService;
import com.bs.bszhsq.utils.MessageType;
import com.bs.bszhsq.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * 文件上传接口
 */
@RestController
@RequestMapping("/file")
@Api(tags ="文件相关接口")
public class FileController {
     @Value("${files.upload.path}")
    private String uploadPath;

     @Resource
     private FileMapper fileMapper;
     @Resource
     private FileService fileService;

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //类型
        String type = FileUtil.extName(originalFilename);
        //大小
        long size = file.getSize();
        //先存储到磁盘
        File file1 = new File(uploadPath);
        if (!file1.exists()){
            file1.mkdirs();
        }
    //文件唯一名字
          String uuid = IdUtil.fastSimpleUUID();
          String fileName=uuid+ StrUtil.DOT +type;
        File file2 = new File(uploadPath +fileName);
        String url;
        //获取文件MD5
        String md5;
        file.transferTo(file2);
        md5 = SecureUtil.md5(file2);

        LambdaQueryWrapper<Files> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Files::getMd5,md5);
        List<Files> fileList = fileMapper.selectList(lqw);
        Files one = fileList.size() == 0 ? null : fileList.get(0);
        if (one!=null){
          file2.delete();
            return one.getUrl();
        }else {

            url="http://localhost:8888/api/file/"+fileName;
            Files files=new Files();
            files.setName(originalFilename);
            files.setType(type);
            //单位kb
            files.setSize(size/1024);
            files.setUrl(url);
            files.setMd5(md5);
            fileMapper.insert(files);
       }
        return url;
    }


    @GetMapping("/{fileName}")
    @ApiOperation(value = "文件下载")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        File file2 = new File(uploadPath +fileName);
        ServletOutputStream outputStream = response.getOutputStream();
      //设置输出流格式
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
        response.setContentType("application/octet-stream");
        outputStream.write(FileUtil.readBytes(file2));
        outputStream.flush();
        outputStream.close();
    }

    @GetMapping("/page")
    @ApiOperation(value = "文件分页查询")
    public R page(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                  @RequestParam(defaultValue = "") String name) {
        IPage<Files> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Files> qw = new QueryWrapper<>();
        if (!"".equals(name)) {
            qw.like("name", name);
        }
        qw.eq("is_delete", MessageType.IS_DELETE_NO.getCode());
        qw.orderByDesc("id");
        IPage<Files> page1 = fileService.page(page, qw);
        return R.success(page1);
    }

    @PostMapping
    @ApiOperation(value = "新增文件")
    public R save(@RequestBody Files files) {
        boolean save = fileService.save(files);
        return R.write(save);
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改文件信息")
    public R update(@RequestBody Files files) {
        boolean update = fileService.updateById(files);
        return R.write(update);
    }
    @PostMapping("/updateEnable")
    @ApiOperation(value = "修改文件停用启用状态")
    public R updateState(@RequestBody Files files){
        boolean b = fileService.updateById(files);
        return R.write(b);
    }



    @PostMapping("/delete")
    @ApiOperation(value = "删除文件")
    public R delete(@RequestBody Long id) {
       Files files=new Files();
       files.setIsDelete(MessageType.IS_DELETE_OK.getCode());
       files.setId(id);
        boolean b = fileService.updateById(files);
        return R.write(b);
    }

    @PostMapping("/deletebatch")
    @ApiOperation(value = "批量删除")
    public R deletebatch(@RequestBody List<Long> ids) {
        for (Long id : ids) {
            Files files=new Files();
            files.setIsDelete(MessageType.IS_DELETE_OK.getCode());
            files.setId(id);
            boolean b = fileService.updateById(files);
        }
        return R.success();
    }
    @AuthAccess
    @GetMapping
    @ApiOperation(value = "查询全部文件")
    public R showAll(){
        LambdaQueryWrapper<Files> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Files::getIsEnable,MessageType.IS_ENABLE_OK.getCode());
        List<Files> list = fileService.list(lqw);
         return R.success(list);
    }

}
